#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

int main(int argc, char **argv)
{
	FILE *fp = 0;
	uint32_t off_set = 0;
	uint8_t data[128 * 3 * 64] = {0};
	uint8_t bit[64][128] = {0};
	uint8_t oled[8][128] = {0};
	uint8_t r, g, b;
	uint32_t rgb = 0;

	if ((fp = fopen("9.bmp", "rb")) == NULL)
	{
		puts("open file error");
		exit(1);
	}

	/* 从文件头到像素数据的偏移 */
	fseek(fp, 10, SEEK_SET);
	fread(&off_set, 4, 1, fp);
	fseek(fp, off_set, SEEK_SET);
	/* 把图像数据读到数组中 */
	fread(data, (128 * 3) * 64, 1, fp);
	fclose(fp);

	/* 把RGB颜色转为黑白两色，然后按行保存到bit数组中 */
	uint32_t base = 128 * 3 * 63;
	for (int row = 0; row < 64; row++)
	{
		for (int i = 0, j = 0; j < 128 * 3; j += 3)
		{
			b = data[base + j];
			g = data[base + j + 1];
			r = data[base + j + 2];

			rgb = (r << 8) + g;
			rgb <<= 8;
			rgb += b;

			bit[row][i++] = rgb < 128 ? 0 : 1;
		}
		base -= (128 * 3);
	}

	/* 数据水平，字节垂直 */
	uint8_t tmp = 0;
	int index = 0;
	for (int i = 0; i < 8; i++)
	{
		for (int col = 0; col < 128; col++)
		{
			tmp = 0;
			for (int set = 0, row = 0 + (i * 8); row < 8 + (i * 8); row++)
			{
				tmp += (bit[row][col] << set++);
			}
			oled[index][col] = tmp;
		}
		index++;
	}

	fp = fopen("9.h", "w");
	int count = 0; // 每行超过16个数就换行
	char buf[8] = {0};
	strcpy(buf, "const uint8_t  = {");
	fwrite(buf, strlen(buf), 1, fp);
	for (int i = 0; i < 8; i++)
	{
		for (int j = 0; j < 128; j++)
		{
			if (oled[i][j] == 0)
				sprintf(buf, "0x00, ");
			else
				sprintf(buf, "%#x, ", oled[i][j]);

			fwrite(buf, strlen(buf), 1, fp);

			if (++count >= 16)
			{
				strcpy(buf, "\n");
				fwrite(buf, strlen(buf), 1, fp);
				count = 0;
			}
		}
	}
	strcpy(buf, "}");
	fwrite(buf, strlen(buf), 1, fp);
	fclose(fp);

	exit(0);
}
